parse = require 'co-body'
# QRCode = require('qrcode')
Promise = require 'bluebird'

config = require('../config')
log = require '../log'
util = require '../util'

xml2js = require "xml2js"
xmlBuilder = new xml2js.Builder(rootName: 'xml', headless: true)
objectToXML = (object)-> xmlBuilder.buildObject(object)
pParseXML = Promise.promisify xml2js.parseString.bind(xml2js)

tppi = require '../tppi/ThirdPartyPaymentIntegration'
mysql = require '../storage/Mysql'

exports.toAlipayFrontCallback = ->
    # TODO
    yield return

# 微信回调
exports.gProcessWeixinCallback = ->
    log.pay.debug 'Got Weixin pay callback'

    data = yield parse.text(this)

    log.tppCallback.info 'Weixin pay callback', data

    unless data?
        log.pay.error 'weixin notify without data!'
        @body = objectToXML({return_code: 'FAIL', return_msg: 'No Body'}).toString()
        return

    try
        data = yield pParseXML data
        data = data.xml

        payTranId = data.out_trade_no[0]
        returnCode = data.return_code[0]
        tpTradeNo = data.transaction_id[0]
        tpResultCode = data.result_code[0]
        buyer = data.openid[0]
        amount = parseInt(data.total_fee[0], 10)

        if returnCode == 'SUCCESS' and tpResultCode == 'SUCCESS'
            newState = tppi.states.Success
        else if tpResultCode == 'FAIL'
            newState = tppi.states.Fail
        else
            log.pay.error 'unrecognizable weixin pay callback result', {returnCode, tpResultCode, tpTradeNo}
            @body = objectToXML({return_code: 'FAIL', return_msg: 'InternalError'}).toString()
            return

        yield from mysql.gUse (conn)->
            ctx = {conn}
            yield from tppi.gUpdatePayTranState(ctx, payTranId, newState, tpTradeNo, amount, buyer)

        @body = objectToXML({return_code: 'SUCCESS', return_msg: 'OK'}).toString()
    catch e
        log.pay.error e, 'gProcessWeixinCallback'
        @body = objectToXML({return_code: 'FAIL', return_msg: 'InternalError'}).toString()

# 处理支付宝支付通知
exports.gProcessAlipayCallback = (data)->
    log.pay.debug 'Got Alipay server notification'

    data = @request.body
    log.tppCallback.info 'Alipay callback', data?.toString()

    try
        unless data?
            log.pay.error 'alipay notify without data!'
            @body = 'fail'
            return

        payTranId = data["out_trade_no"]
        tpResultCode = data["trade_status"]
        tpTradeNo = data["trade_no"]
        amount = data['total_fee'] * 100 # 单位元到分
        buyer = data['buyer_email']

        if tpResultCode == 'TRADE_SUCCESS' || tpResultCode == 'TRADE_FINISHED'
            newState = tppi.states.Success
        else
            log.pay.error 'unrecognizable alipay pay callback result', {tpResultCode, tpTradeNo}
            @body = 'fail'
            return

        yield from mysql.gUse (conn)->
            ctx = {conn}
            yield from tppi.gUpdatePayTranState(ctx, payTranId, newState, tpTradeNo, amount, buyer)
        @body = "success"
    catch e
        log.pay.error e, 'gProcessAlipayCallback'
        @body = 'fail'